package bid.web;

import bid.dao.UserDao;
import bid.dao.impl.UserDaoImpl;
import bid.entity.User;
import bid.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet(value = "/users")
public class UserServlet extends HttpServlet {
    UserDao userDao = new UserDaoImpl();

    public UserServlet(){
        System.out.println("UserServlet被构造了");
    }
    @Override
    public void init() throws ServletException {
        System.out.println("Uservlet初始化");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //请求先到这里
        System.out.println("进入了Service....");
//        if(req.getMethod().equals("GET")){
//            doGet();
//        }else if(req.getMethod().equals("POST")){
//            doPost();
//        }
        super.service(req, resp);
    }

    @Override
    public void destroy() {
        System.out.println("UserServlet销毁了");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        //request.getMethod()
        System.out.println("进入了:doGet");
        //int pageNo=Integer.parseInt(request.getParameter("pageNo"));
        String name= StringUtils.trim(request.getParameter("name"));
        String username=StringUtils.trim(request.getParameter("username"));
        Date start=StringUtils.toDate(request.getParameter("start"));
        Date end=StringUtils.toDate(request.getParameter("end"));
        int pageNo = StringUtils.toInt(request.getParameter("pageNo"), 1);
        int pageSize=10;
        List<User> users = userDao.search(pageNo, pageSize, name, username, start, end);

        long total=userDao.searchTotal(name,username,start,end);

        long pageNums=total/pageSize+(total%pageSize==0?0:1);//求页数

        request.setAttribute("users",users);
        request.setAttribute("pageNums",pageNums);
        request.setAttribute("pageNo",pageNo);
        request.setAttribute("name",name);
        request.setAttribute("username",username);
        request.setAttribute("start",start);
        request.setAttribute("end",end);
        //转发
        request.getRequestDispatcher("/users.jsp").forward(request,resp);
        //重定向
        //resp.sendRedirect("xxx.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
